package com.yunjian.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunjian.common.utils.*;
import com.yunjian.core.entity.Goods;
import com.yunjian.core.entity.SysOrder;
import com.yunjian.core.entity.SysOrderDetail;
import com.yunjian.core.entity.SysUserEntity;
import com.yunjian.core.mapper.SysOrderMapper;
import com.yunjian.core.service.IGoodsService;
import com.yunjian.core.service.ISysOrderDetailService;
import com.yunjian.core.service.ISysOrderService;
import com.yunjian.core.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 经销商采购单 服务实现类
 * </p>
 *
 * @author laizhiwen
 * @since 2020-06-23
 */
@Service
public class SysOrderServiceImpl extends ServiceImpl<SysOrderMapper, SysOrder> implements ISysOrderService {

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ISysOrderDetailService sysOrderDetailService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String orderNo = StringUtil.obj2String(params.get("orderNo"));
        String email = StringUtil.obj2String(params.get("email"));
        Integer isAdmin = Integer.parseInt(params.get("isAdmin").toString());
        QueryWrapper<SysOrder> queryWrapper = new QueryWrapper<SysOrder>();
        if(StringUtils.isNotBlank(orderNo)){
            queryWrapper.like("order_no", orderNo);
        }
        if(StringUtils.isNotBlank(email)){
            queryWrapper.like("email", email);
        }

        if(isAdmin.intValue() == 0){
            queryWrapper.eq("user_id", HttpContextUtils.getLoginSysUserEntity().getUserId().intValue());
        }else{
            queryWrapper.ne("status", 0);
        }
        queryWrapper.eq("delete_flag", 1).orderByDesc("create_time");
        IPage<SysOrder> page = this.page(new Query<SysOrder>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    @Override
    public void createOrder(Map<String, Object> params) {
        List<Map<String, Object>> goodsList = (List<Map<String, Object>>)params.get("paramGoodsList");
        if(goodsList.isEmpty()){
            return;
        }
        SysUserEntity sysUserEntity = HttpContextUtils.getLoginSysUserEntity();
        SysUserEntity user = sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("user_id", sysUserEntity.getUserId()));
        SysOrder sysOrder = new SysOrder();
        String orderNo = createOrderNo();
        BigDecimal totalPrice = BigDecimal.ZERO;
        List<SysOrderDetail> details = new ArrayList<>();
        for (Map<String, Object> item : goodsList){
            Integer goodsId = Integer.parseInt(item.get("goodsId").toString());
            Integer amount = Integer.parseInt(item.get("amount").toString());;
            Goods goods = goodsService.getOne(new QueryWrapper<Goods>().eq("id", goodsId));
            SysOrderDetail detail = new SysOrderDetail();
            detail.setGoodsId(goodsId);
            detail.setGoodsName(goods.getName());
            detail.setGoodsKind(goods.getKind());
            detail.setGoodsType(StringUtils.isEmpty(goods.getType()) ? null : Integer.parseInt(goods.getType()));
            detail.setOrderNo(orderNo);
            BigDecimal price = goods.getIsDiscount() == 0 ? goods.getPrice() : goods.getDiscountPrice();

            BigDecimal dTotalPrice = price.multiply(BigDecimal.valueOf(amount.doubleValue()));
            detail.setUnitPrice(price);
            detail.setAmount(amount);
            detail.setTotalPrice(dTotalPrice);
            details.add(detail);
            totalPrice = totalPrice.add(dTotalPrice);
        }

        if(!details.isEmpty()){
            sysOrderDetailService.saveBatch(details);

            sysOrder.setOrderNo(orderNo);
            sysOrder.setCompany(user.getCompany());
            sysOrder.setEmail(user.getEmail());
            sysOrder.setMobile(user.getMobile());
            sysOrder.setStatus(0);
            sysOrder.setUserId(user.getUserId().intValue());
            sysOrder.setUserName(user.getUsername());
            sysOrder.setCreateTime(new Date());
            sysOrder.setDeleteFlag(1);
            sysOrder.setTotalPrice(totalPrice);
            this.save(sysOrder);
        }
    }

    private String createOrderNo(){
        String prefix = "SO" + DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN_V);
        return prefix + (int)((Math.random()*9+1) * 10000);
    }

    @Override
    public PageUtils queryGoodsByPage(Map<String, Object> params) {
        String name = (String) params.get("name");

        QueryWrapper<Goods> queryWrapper = new QueryWrapper<Goods>();
        queryWrapper.eq("status", 1)
                .eq("is_admin", 1)
                .eq("delete_flag", 1)
                .orderByDesc("create_time");
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }

        IPage<Goods> page = goodsService.page(new Query<Goods>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }
}
